﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YouWei.Infrastructure.Dto;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace ServiceContainer.Jobs
{
    public class VehicleLicenseCheckJob : IJob
    {
        VehicleLicenseService vehService = new VehicleLicenseService();
        UserInfoService userService = new UserInfoService();
        InterfaceDataVehicleService idvService = new InterfaceDataVehicleService();

        private int CheLeXingDataCacheTime {
            get {
                return Convert.ToInt32(ConfigHelper.GetAppSettingValue("CheLeXingDataCacheTime"));
            }
        }

        public void Execute(IJobExecutionContext context)
        {
            List<VehicleLicense> list = vehService.GetInspectList();
            foreach (var item in list)
            {
                if (IsExist(item.PlateNo))
                {
                    SetVehicleUserStatus(item);
                }
                else
                {
                    GetVehicleInfoSetStatus(item);
                }
            }
            
        }

        /// <summary>
        /// 获取车辆信息并设置行驶证、用户为有效
        /// </summary>
        /// <param name="vehObj"></param>
        private void GetVehicleInfoSetStatus(VehicleLicense vehObj)
        {
            var result = ExternalInterfaceService.GetCheLeXingVehicleInfo(new ReqCheLeXingVehicle()
            {
                hpzl = "02",
                hphm = vehObj.PlateNo
            });
            if (result.code == 1)
            {
                SetVehicleUserStatus(vehObj);
            }
            else
            {
                vehObj.VehicleStatus = 3;
                vehService.Update(vehObj);
            }
        }

        /// <summary>
        /// 查询是否已经获取过当前车辆信息 
        /// </summary>
        /// <param name="plate"></param>
        /// <returns></returns>
        private bool IsExist(string plate)
        {
            InterfaceDataVehicle info = idvService.GetLocalSuccessRecord("02", plate, DateTime.Now.AddMinutes(-CheLeXingDataCacheTime));
            if (info != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 设置行驶证、用户有效状态
        /// </summary>
        /// <param name="vehObj"></param>
        private void SetVehicleUserStatus(VehicleLicense vehObj)
        {
            vehObj.VehicleStatus = 2;
            vehService.Update(vehObj);
            userService.SetUserValid(vehObj.UserID);
        }
    }
}
